package com.uenpay.im.ui.old.activity.group;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.common.ImageUtil;
import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.GroupMemberManager;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.GroupMemberEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.qyx.android.weight.view.MyGridView;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.TalkApplyFriendsListActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.TakePhotoActivity;
import com.uenpay.im.ui.old.activity.contacts.ReportContactsOrGroupActivity;
import com.uenpay.im.ui.old.activity.contacts.UserDetailActivity;
import com.uenpay.im.ui.old.activity.funds.FundsManageActivity;
import com.uenpay.im.ui.old.activity.personal.ClipImageActivity;
import com.uenpay.im.ui.old.activity.personal.MeDetailActivity;
import com.uenpay.im.ui.old.activity.personal.QRCodeActivity;
import com.uenpay.im.adapter.ParticipantAdapter;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.IRemoveGroupMemberListener;
import com.uenpay.im.callback.OnUploadFile2Listener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.invokeitems.GetGroupMessageDetail;
import com.uenpay.im.invokeitems.UploadFile;
import com.uenpay.im.view.PictureShowActivity;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * 群聊详情
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 *
 */
public class GroupDetailActivity extends BaseActivity {
	private UpdateAvatarBroadcast mUpdateAvatarBroadcast = null;
	private GroupMangerHandler mGroupMangerHandler = new GroupMangerHandler();
	private GroupTalkDbManager groupTalkDbManager = new GroupTalkDbManager();
	private GroupMemberManager GroupMemberManager = new GroupMemberManager();
	private TalkMsgManager takeMsgManager = new TalkMsgManager();
	private TopListMsgManager topListMsgManager = new TopListMsgManager();
	/**
	 * 修改群名称
	 */
	private final int REQUSET_ALTER_GROUP_NAME = 2;
	/**
	 * 添加群成员
	 */
	private final int ADD_GROUP_CLASSMATES = 3;
	/**
	 * 修改我在该群昵称
	 */
	private final int UPDATE_MY_NAME_IN_GROUP = 4;
	/**
	 * 修改群简介
	 */
	private final int UPDATE_GROUP_INTRODUCE = 5;
	/**
	 * 设置新群主
	 */
	private final int SET_GROUP_NEW_MANAGER = 6;
	/**
	 * 删除群成员
	 */
	private final int DELETE_GROUP_MEMBERS = 7;
	/**
	 * 设置新群主并退出
	 */
	private final int DELETE_AND_SET_NEW_MANAGER = 8;
	/**
	 * 退出群聊
	 */
	private final int QUIT_GROUP_TALK = 101;
	/**
	 * 设置是否显示群成员昵称
	 */
	private final int UPDATE_SHOW_GROUP_MEMBER_NAME = 102;
	private final int CHOOSE_TAKE_PHOTO_REQUEST_CODE = 110;
	private final int CHOOSE_IMAGE_REQUEST_CODE = 111;
	private final int CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE = 112;
	private MyGridView _participants;
	private ParticipantAdapter adapter;
	private boolean isCreator = false;
	private ArrayList<GroupMemberEntity> participants = new ArrayList<GroupMemberEntity>();
	private GroupTalkEntity groupTalk = new GroupTalkEntity();

	private int is_admin;
	private String groupName;
	private RoundImageView talk_detail_avatar, talk_detail_creater_avatar;
	private TextView talk_detail_name, talk_detail_introduce_tv, my_name;
	private String chatId;
	private int join_status = -1;
	private TextView talk_detail_max_count;
	private View tran_loading;
	private String creator_cust_id = "";
	private ImageButton new_msg_notify_btn, show_member_name_btn,
			invitation_memebers_btn;
	private LinearLayout bottom_layout, new_msg_layout;
	private Button talk_detail_apply_join_btn, delete_and_exit_btn;
	private RelativeLayout audit_new_members_layout, transfer_group_layout,
			group_funds_manager_layout;
	private int is_remind = 0, is_show_group_member_name = 0,
			is_invita_members = 1;
	private int isShowMemberName = -1, isUpdateNameInGroup = -1;
	private ScrollView scroll_view;
	private int chatType;
	private String amount;
	private TextView title_textview;
	private boolean isFundsGroup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isFullScreen=true;
		super.onCreate(savedInstanceState);
	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_group_detail_layout;
	}

	@Override
	public void initView(View view) {
		chatId = getIntent().getStringExtra("to_id");
		initView();
		initData();
		getNewGroup(chatId);
		initListener();
	}

	protected void initView() {
		title_textview = ((TextView) findViewById(R.id.title_textview));
		title_textview.setText(getResources().getString(R.string.group_detail));
		talk_detail_max_count = (TextView) findViewById(R.id.talk_detail_max_count);
		new_msg_notify_btn = (ImageButton) findViewById(R.id.new_msg_notify_btn);
		show_member_name_btn = (ImageButton) findViewById(R.id.show_member_name_btn);
		invitation_memebers_btn = (ImageButton) findViewById(R.id.invitation_memebers_btn);
		talk_detail_avatar = (RoundImageView) findViewById(R.id.talk_detail_avatar);
		talk_detail_creater_avatar = (RoundImageView) findViewById(R.id.talk_detail_creater_avatar);
		talk_detail_name = (TextView) findViewById(R.id.talk_detail_name);
		_participants = (MyGridView) findViewById(R.id.participants);
		talk_detail_introduce_tv = (TextView) findViewById(R.id.talk_detail_introduce_tv);
		my_name = (TextView) findViewById(R.id.my_name);
		bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
		new_msg_layout = (LinearLayout) findViewById(R.id.new_msg_layout);
		talk_detail_apply_join_btn = (Button) findViewById(R.id.talk_detail_apply_join_btn);
		delete_and_exit_btn = (Button) findViewById(R.id.delete_and_exit_btn);
		tran_loading = (View) findViewById(R.id.loading);
		transfer_group_layout = (RelativeLayout) findViewById(R.id.transfer_group_layout);
		audit_new_members_layout = (RelativeLayout) findViewById(R.id.audit_new_members_layout);
		group_funds_manager_layout = (RelativeLayout) findViewById(R.id.group_funds_manager_layout);
		scroll_view = (ScrollView) findViewById(R.id.scroll_view);
	}

	protected void initListener() {
		findViewById(R.id.back_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						setBackResult();
					}
				});

		talk_detail_avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String path = APIConfiguration.getAvatarUrlBig(chatId,
						PacketType.GROUP);
				ArrayList<String> imgs = new ArrayList<String>();
				Intent show = new Intent(GroupDetailActivity.this,
						PictureShowActivity.class);
				show.putExtra("content", path);
				imgs.add(path);
				show.putStringArrayListExtra("imgList", imgs);
				startActivity(show);
			}
		});

		new_msg_notify_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (is_remind == 1) {
					is_remind = 0;
				} else {
					is_remind = 1;
				}
				setGroupNewMsgPush();
			}
		});
		show_member_name_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (is_show_group_member_name == 1) {
					is_show_group_member_name = 0;
				} else {
					is_show_group_member_name = 1;
				}
				updateShowMemberNameBtnBg();
				groupTalkDbManager.updateIsShowGroupMemenberName(
						Long.valueOf(chatId), is_show_group_member_name);
			}
		});

		invitation_memebers_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				is_invita_members = is_invita_members == 1 ? 0 : 1;
				// 修改邀请好友
				setInvitaMemebers();
			}
		});
		findViewById(R.id.talk_detail_report_group_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (!TextUtils.isEmpty(chatId)) {
							Intent intent = new Intent(
									GroupDetailActivity.this,
									ReportContactsOrGroupActivity.class);
							intent.putExtra("to_cust_id", chatId);
							intent.putExtra("type", 2);
							startActivity(intent);
						}
					}
				});
		findViewById(R.id.talk_detail_update_avatar_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (isCreator) {
							updateGroupAvatarDialog();
						}
					}
				});
		findViewById(R.id.group_name_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (isCreator) {
							Intent intent = new Intent(
									GroupDetailActivity.this,
									EditGroupInfoActivity.class);
							intent.putExtra("chat_id", chatId);
							intent.putExtra("type", 1);
							intent.putExtra("oldStr", talk_detail_name
									.getText().toString());
							startActivityForResult(intent,
									REQUSET_ALTER_GROUP_NAME);
						} else {
							updateGroupInfoDialog(1);
						}
					}
				});

		findViewById(R.id.talk_detail_introduce_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (isCreator) {
							Intent intent = new Intent(
									GroupDetailActivity.this,
									EditGroupInfoActivity.class);
							intent.putExtra("chat_id", chatId);
							intent.putExtra("type", 3);
							intent.putExtra("oldStr", talk_detail_introduce_tv
									.getText().toString());
							startActivityForResult(intent,
									UPDATE_GROUP_INTRODUCE);
						} else {
							updateGroupInfoDialog(2);
						}
					}
				});
		findViewById(R.id.my_name_in_the_group_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(GroupDetailActivity.this,
								EditGroupInfoActivity.class);
						intent.putExtra("chat_id", chatId);
						intent.putExtra("type", 2);
						intent.putExtra("oldStr", my_name.getText().toString());
						startActivityForResult(intent, UPDATE_MY_NAME_IN_GROUP);

					}
				});

		findViewById(R.id.talk_detail_max_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (!TextUtils.isEmpty(chatId)) {
							transferGroupManger(SET_GROUP_NEW_MANAGER,3);
						}
					}
				});
		findViewById(R.id.talk_detail_creater_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (!TextUtils.isEmpty(creator_cust_id)
								&& creator_cust_id.equals(IMApplication
										.getCustId())) {
							Intent intent = new Intent();
							intent.setClass(GroupDetailActivity.this,
									MeDetailActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent();
							intent.setClass(GroupDetailActivity.this,
									UserDetailActivity.class);
							intent.putExtra("cust_id", creator_cust_id);
							startActivity(intent);
						}
					}
				});
		findViewById(R.id.talk_detail_clear_msg_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						clearMsg();
					}
				});

		delete_and_exit_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!TextUtils.isEmpty(chatId)) {
					if (isCreator) {
						transferGroupManger(DELETE_AND_SET_NEW_MANAGER,1);
					} else {
						deleteGroupDialog();
					}
				}

			}
		});

		// send_msg_btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// if (TextUtils.isEmpty(chatId)) {
		// return;
		// }
		// Intent intent = new Intent(GroupDetailActivity.this,
		// ChatActivity.class);
		// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// Bundle bu = new Bundle();
		// SessionModel sessionModel = new SessionModel();
		// sessionModel.setSessionId(Long.valueOf(chatId));
		// sessionModel.setSessionType(PacketType.GROUP);
		// if(groupTalk.org_type_id == 3){
		// sessionModel.setOperationType(4);
		// }
		// bu.putParcelable("session", sessionModel);
		// intent.putExtras(bu);
		// startActivity(intent);
		// finish();
		// }
		// });
		group_funds_manager_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (creator_cust_id.equals(IMApplication.getCustId())
						&& chatType == 3) {
					Intent intent = new Intent(GroupDetailActivity.this,
							FundsManageActivity.class);
					intent.putExtra("chat_id", chatId);
					intent.putExtra("amount", amount);
					startActivity(intent);
				}
			}
		});
		talk_detail_apply_join_btn
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						applyJoinGroup();
					}
				});
		findViewById(R.id.group_code_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent();
						intent.setClass(GroupDetailActivity.this,
								QRCodeActivity.class);
						intent.putExtra("cust_id", chatId);
						intent.putExtra("cust_name", groupName);
						startActivity(intent);
					}
				});
		audit_new_members_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(GroupDetailActivity.this,
						TalkApplyFriendsListActivity.class);
				intent.putExtra("group_id", chatId);
				startActivity(intent);
			}
		});
		transfer_group_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				transferGroupManger(SET_GROUP_NEW_MANAGER, 1);
//				Intent intent = new Intent(GroupDetailActivity.this,
//						GroupMemberActivity.class);
//				intent.putExtra("group_id", chatId);
//				intent.putExtra("creator_cust_id", creator_cust_id);
//				intent.putExtra("type", 1);
//				intent.putExtra("isFundsGroup", isFundsGroup);
//				startActivityForResult(intent, SET_GROUP_NEW_MANAGER);
			}
		});
		_participants
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						GroupMemberEntity participantEntity = adapter
								.getItem(position);

						boolean is_add = false;
						boolean is_del = false;
						if (join_status == 1 && isCreator
								&& position == adapter.getCount() - 1) {
							is_del = true;
						} else if (join_status == 1 && isCreator
								&& position == adapter.getCount() - 2) {
							is_add = true;
						} else if (join_status == 1 && !isCreator
								&& position == adapter.getCount() - 1) {
							is_add = true;
						} else {
							if (participantEntity != null
									&& participantEntity.cust_id != 0) {
								if ((participantEntity.cust_id + "")
										.equals(IMApplication.getCustId())) {
									Intent intent = new Intent();
									intent.setClass(GroupDetailActivity.this,
											MeDetailActivity.class);
									startActivity(intent);
								} else {
									Intent intent = new Intent();
									intent.setClass(GroupDetailActivity.this,
											UserDetailActivity.class);
									intent.putExtra("cust_id",
											participantEntity.cust_id + "");
									GroupDetailActivity.this
											.startActivity(intent);
								}
							}
						}

						if (is_del) {
							Intent intent = new Intent();
							intent.setClass(GroupDetailActivity.this,
									DeleteGroupMemberActivity.class);
							intent.putExtra("group_id", chatId);
							startActivityForResult(intent, DELETE_GROUP_MEMBERS);
						}

						if (is_add) {
							int groupType = GroupType.NORMAL_GROUP;
							if (chatType == 3) {
								groupType = GroupType.AMOUNT_GORUP;
							}
							Intent intent = new Intent();
							intent.setClass(GroupDetailActivity.this,
									AddGroupMemberActivity.class);
							intent.putExtra("group_id", chatId);
							intent.putExtra("group_type", groupType);
							startActivityForResult(intent, ADD_GROUP_CLASSMATES);
						}
					}
				});

	}

	/**
	 * 设置新群主
	 */
	private void transferGroupManger(int requestCode,int type) {
		Intent intent = new Intent(GroupDetailActivity.this,
				GroupMemberActivity.class);
		intent.putExtra("group_id", chatId);
		intent.putExtra("creator_cust_id", creator_cust_id);
		intent.putExtra("type", type);
		intent.putExtra("isFundsGroup", isFundsGroup);
		startActivityForResult(intent, requestCode);
	}

	public void initData() {

		GroupTalkEntity group_talk = groupTalkDbManager
				.queryGroupByGroupId(Long.valueOf(chatId));
		is_remind = group_talk.is_remind;
		is_show_group_member_name = group_talk.is_show_member_name;
		isShowMemberName = group_talk.is_show_member_name;
		if (is_remind == 1) {
			new_msg_notify_btn
					.setBackgroundResource(R.drawable.img_button_toggle_on);
		} else {
			new_msg_notify_btn
					.setBackgroundResource(R.drawable.img_button_toggle_off);
		}
		updateShowMemberNameBtnBg();
	}

	private void updateShowMemberNameBtnBg() {
		if (is_show_group_member_name == 1) {
			show_member_name_btn
					.setBackgroundResource(R.drawable.img_button_toggle_on);
		} else {
			show_member_name_btn
					.setBackgroundResource(R.drawable.img_button_toggle_off);
		}
	}

	private void updateInvitaMemebers() {
		if (is_invita_members == 1) {
			invitation_memebers_btn
					.setBackgroundResource(R.drawable.img_button_toggle_on);
		} else {
			invitation_memebers_btn
					.setBackgroundResource(R.drawable.img_button_toggle_off);
		}
	}

	private void setInvitaMemebers() {
		GroupMangerHandler.setInvitMember(chatId, is_invita_members,
				new GroupMangerHandler.IAcceptJoinGroupListener() {

					@Override
					public void onAcceptJoinGroupResult(int status, String msg) {
						if (status == HttpInvokeResultCode.RESULT_OK) {
							updateInvitaMemebers();
						} else if (!TextUtils.isEmpty(msg)) {
							IMApplication.showToast(msg);
						}
					}
				});
	}

	private void getGroupData() {
		groupTalk = groupTalkDbManager
				.queryGroupByGroupId(Long.valueOf(chatId));
		participants = GroupMemberManager.queryAll(Long.valueOf(chatId));
		if (groupTalk != null) {
			is_admin = groupTalk.is_admin;
			join_status = groupTalk.join_status;
			creator_cust_id = groupTalk.creator_cust_id;
			if (is_admin == 1) {
				isCreator = true;
			} else {
				isCreator = false;
			}
		}
		sortMembers();
	}

	class GetDataTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {

			try {
				getGroupData();
			} catch (Exception e) {
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			showCust();
		}
	}

	private void showCust() {
		if (participants == null) {
			return;
		}

		if (groupTalk != null) {
			groupName = groupTalk.group_name;
			talk_detail_name.setText(groupTalk.group_name);
			if (!TextUtils.isEmpty(groupTalk.introduce)) {
				talk_detail_introduce_tv.setText(groupTalk.introduce);
				talk_detail_introduce_tv.setVisibility(View.VISIBLE);
			}
			talk_detail_avatar.SetUrl(APIConfiguration.getAvatarUrlNormal(
					chatId, PacketType.GROUP), true);
			talk_detail_max_count
					.setText(MessageFormat
							.format(getResources().getString(
									R.string.group_all_member),
									groupTalk.has_count));
			my_name.setText(groupTalk.my_name_in_group);
			title_textview.setText(getResources().getString(
					R.string.group_detail)
					+ "(" + groupTalk.has_count + ")");
			String url = APIConfiguration.getAvatarUrlNormal(
					groupTalk.creator_cust_id, PacketType.PERSONAL);
			talk_detail_creater_avatar.SetUrl(url);
			if (join_status == 1) {
				bottom_layout.setVisibility(View.VISIBLE);
				/**
				 * 申请加入群聊
				 */
				talk_detail_apply_join_btn.setVisibility(View.GONE);
				delete_and_exit_btn.setVisibility(View.VISIBLE);
			} else {
				new_msg_layout.setVisibility(View.GONE);
				delete_and_exit_btn.setVisibility(View.GONE);
				talk_detail_apply_join_btn.setVisibility(View.GONE);
				bottom_layout.setVisibility(View.GONE);
			}
			if (isCreator) {
				findViewById(R.id.group_manager_layout).setVisibility(
						View.VISIBLE);
			} else {
				delete_and_exit_btn.setText(getResources().getString(
						R.string.delete_and_exit));
			}

			if (!TextUtils.isEmpty(groupTalk.group_info_json)) {
				try {
					JSONObject json = new JSONObject(groupTalk.group_info_json);
					if (json.has("amount")) {
						amount = json.optString("amount");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			// amount = groupTalk.spare_field;
			chatType = groupTalk.org_type_id;
			/** 经费群 **/
			if (groupTalk.org_type_id == 3) {
				isFundsGroup = true;
				group_funds_manager_layout.setVisibility(View.VISIBLE);
			} else {
				isFundsGroup = false;
				group_funds_manager_layout.setVisibility(View.GONE);
			}

			if (!TextUtils.isEmpty(groupTalk.group_info_json)) {
				try {
					JSONObject json = new JSONObject(groupTalk.group_info_json);
					if (json.has("isopen")) {
						is_invita_members = json.optInt("isopen");
						if (!isCreator) {
							join_status = is_invita_members;
						}
						updateInvitaMemebers();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		if (adapter == null) {
			adapter = new ParticipantAdapter(GroupDetailActivity.this,
					participants, isCreator, join_status);
			_participants.setAdapter(adapter);
		} else {
			adapter.setData(participants);
		}
		scroll_view.setVisibility(View.VISIBLE);
	}

	private void getNewGroup(final String chatId) {
		tran_loading.setVisibility(View.VISIBLE);

		mGroupMangerHandler.getGroupDetail(chatId,
				new GroupMangerHandler.IGetGroupDetailListener() {

					@Override
					public void onGetGroupDetailResult(
							GetGroupMessageDetail.GetGroupMessageDetailResult result) {
						if (result != null
								&& result.status == HttpInvokeResultCode.RESULT_OK) {
							String path = APIConfiguration.getAvatarUrlBig(
									chatId, PacketType.GROUP);
							HttpStreamCache.getInstance()
									.ClearCacheBitmap(path);
							HttpStreamCache.getInstance().ClearCacheBitmap(
									APIConfiguration.getAvatarUrlNormal(chatId,
											PacketType.GROUP));
							participants = result.participants;
							is_admin = result.groupTalk.is_admin;
							join_status = result.groupTalk.join_status;
							if (is_admin == 1) {
								isCreator = true;
							} else {
								isCreator = false;
							}
							creator_cust_id = result.groupTalk.creator_cust_id
									+ "";
							sortMembers();
							groupName = result.groupTalk.group_name;
							groupTalk = result.groupTalk;
							Message msgResult = myHandler.obtainMessage();
							msgResult.obj = result;
							msgResult.what = 1;
							myHandler.sendMessage(msgResult);
							myHandler.sendEmptyMessage(0);
						} else {
							myHandler.sendEmptyMessage(0);
							if (result != null
									&& result.status == HttpInvokeResultCode.GROUP_DELETED) {
								myHandler.sendEmptyMessage(2);
							} else {
								new GetDataTask().execute();
							}
						}
					}
				});
//
//		OnGetGroupTalk mGetGroupTalk = new OnGetGroupTalk() {
//
//			@Override
//			public void onSucceeful(String status,
//					GetGroupMessageDetailResult result) {
//
//				String path = APIConfiguration.getAvatarUrlBig(chatId,
//						PacketType.GROUP);
//				HttpStreamCache.getInstance().ClearCacheBitmap(path);
//				HttpStreamCache.getInstance().ClearCacheBitmap(
//						APIConfiguration.getAvatarUrlNormal(chatId,
//								PacketType.GROUP));
//
//				participants = result.participants;
//				is_admin = result.groupTalk.is_admin;
//				join_status = result.groupTalk.join_status;
//				if (is_admin == 1) {
//					isCreator = true;
//				} else {
//					isCreator = false;
//				}
//				creator_cust_id = result.groupTalk.creator_cust_id + "";
//				sortMembers();
//				groupName = result.groupTalk.group_name;
//				groupTalk = result.groupTalk;
//				Message msgResult = myHandler.obtainMessage();
//				msgResult.obj = result;
//				msgResult.what = 1;
//				myHandler.sendMessage(msgResult);
//				myHandler.sendEmptyMessage(0);
//			}
//
//			@Override
//			public void onFailed(String status) {
//				myHandler.sendEmptyMessage(0);
//				if (!TextUtils.isEmpty(status)
//						&& status.equals(HttpInvokeResultCode.GROUP_DELETED
//								+ "")) {
//					myHandler.sendEmptyMessage(2);
//				} else {
//					new GetDataTask().execute();
//				}
//			}
//		};
//
//		mGroupMangerHandler.getGroupDetail(chatId, mGetGroupTalk);

	}

	private void sortMembers() {
		GroupMemberEntity groupMemberEntity = null;
		for (int i = 0, size = participants.size(); i < size; i++) {
			if (creator_cust_id.equals(participants.get(i).cust_id + "")) {
				groupMemberEntity = participants.get(i);
				participants.remove(i);
				break;
			}
		}

		if (groupMemberEntity != null) {
			participants.add(0, groupMemberEntity);
		}
	}

	public Handler myHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			if (arg0.what == 2) {
				updateGroupInfoDialog(3);
			} else if (arg0.what == 1) {
				showCust();
			} else if (arg0.what == 0) {
				if (tran_loading != null) {
					tran_loading.setVisibility(View.GONE);
				}
			}

			return false;
		}
	});

	/**
	 * 修改群资料提示框
	 * @param type 1：修改群名称 2：修改群介绍3：删除群聊
	 */
	private void updateGroupInfoDialog(final int type) {
		boolean isCancelable = true;
		int contentStrResId = -1;
		if (type == 1) {
			contentStrResId = R.string.update_group_name_info;
		} else if (type == 2) {
			contentStrResId = R.string.update_group_intro_info;
		} else if (type == 3) {
			isCancelable = false;
			contentStrResId = R.string.group_is_deleted;
		}
		DialogUtility.showSingleBtnDialog(GroupDetailActivity.this,
				contentStrResId, R.string.i_got, isCancelable,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						if (type == 3) {
							finish();
						}
					}
				});

	}

	private void clearMsg() {
		DialogUtility.showDialog(GroupDetailActivity.this,
				R.string.delete_messages_log_group_in_talk, R.string.yes,
				R.string.no, true, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						delDBmsg(true);
						IMApplication.showToast(getResources().getString(
								R.string.delete_completed));
					}
				});

	}

	public void delDBmsg(boolean is_logout) {
		takeMsgManager.deleteGroupAllMsgByGroupId(Long.valueOf(chatId));
		if (is_logout) {
			topListMsgManager.deleteByMsg(Long.valueOf(chatId),
					Integer.valueOf(PacketType.GROUP));
		} else {
			topListMsgManager.updateTopMsgByField(Long.valueOf(chatId),
					PacketType.GROUP, DBTopMsgColumns.CONTENT, "");
		}
		Intent update_top = new Intent(BroadcastAction.CLEAR_TALK_MSG_ACTION);
		sendBroadcast(update_top);

		Intent intent = new Intent();
		intent.setAction(BroadcastAction.CLEAR_MSG_ACTION);
		sendBroadcast(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE) {
				if (data == null) {
					return;
				}
				String pic_path = data.getStringExtra("pic_path");
				if (!TextUtils.isEmpty(pic_path)) {
					Bitmap photo = ImageUtil.CompressImageSameRadioScale(
							pic_path, 100, 720, 720);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					photo.compress(Bitmap.CompressFormat.JPEG, 80, baos);

					byte[] bytes = baos.toByteArray();
					tran_loading.setVisibility(View.VISIBLE);
					String url = APIConfiguration.getBaseUrl()
							+ "Chat/Chat/setAvatar?chatid=" + chatId + "&"
							+ APIConfiguration.getCustIdAndToken();
					uploadAvatar(bytes, url);
					if (photo != null && !photo.isRecycled()) {
						photo.recycle();
					}
				}
			} else if (requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
				@SuppressWarnings("unchecked")
				ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data
						.getSerializableExtra("gl_arr");
				if (select_gl_arr.size() > 0) {
					for (int i = 0; i < select_gl_arr.size(); i++) {
						String path = select_gl_arr.get(i).getPath();
						Intent intent = new Intent(GroupDetailActivity.this,
								ClipImageActivity.class);
						intent.putExtra("picPath", path);
						startActivityForResult(intent,
								CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
					}
				}

			} else if (requestCode == CHOOSE_TAKE_PHOTO_REQUEST_CODE) {
				String path = data.getStringExtra("big_pic_filename");
				Intent intent = new Intent(GroupDetailActivity.this,
						ClipImageActivity.class);
				intent.putExtra("picPath", path);
				startActivityForResult(intent,
						CHOOSE_CROP_FROM_CAMERA_REQUEST_CODE);
			} else if (requestCode == REQUSET_ALTER_GROUP_NAME) {
				groupTalk = groupTalkDbManager.queryGroupByGroupId(Long
						.valueOf(chatId));
				talk_detail_name.setText(groupTalk.group_name);
			} else if (requestCode == ADD_GROUP_CLASSMATES) {
				if (groupTalk.org_type_id == GroupType.AMOUNT_GORUP) {
					showAddGroupMemeberDialog();
				} else {
					if (adapter != null) {
						adapter = null;
					}
					if (participants != null) {
						participants.clear();
					}
					tran_loading.setVisibility(View.VISIBLE);
					getNewGroup(chatId);
				}

			} else if (requestCode == UPDATE_MY_NAME_IN_GROUP) {
				isUpdateNameInGroup = 1;
				updateMyNameInGroupMenember();
				my_name.setText(data.getStringExtra("result"));
			} else if (requestCode == UPDATE_GROUP_INTRODUCE) {
				talk_detail_introduce_tv.setText(data.getStringExtra("result"));
				talk_detail_introduce_tv.setVisibility(View.VISIBLE);
			} else if (requestCode == SET_GROUP_NEW_MANAGER
					|| requestCode == DELETE_GROUP_MEMBERS) {
				if (requestCode == DELETE_GROUP_MEMBERS) {
					tran_loading.setVisibility(View.VISIBLE);
					getNewGroup(chatId);
				} else {
					finish();
				}
			} else if (requestCode == DELETE_AND_SET_NEW_MANAGER) {
				/** 群主转让群并退出 **/
				exitGroup();
			}
		}
	}

	private void deleteGroupDialog() {
		int ContentStrResId = -1;
		if (isCreator) {
			ContentStrResId = R.string.confirm_to_quit_this_group;
		} else {
			ContentStrResId = R.string.delete_this_group;
		}
		DialogUtility.showDialog(GroupDetailActivity.this, ContentStrResId,
				R.string.yes, R.string.no, true, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						if (isCreator) {
							deleteGroup();
						} else {
							exitGroup();
						}
					}
				});

	}

	private void deleteGroup() {
		tran_loading.setVisibility(View.VISIBLE);
		if (mGroupMangerHandler == null) {
			mGroupMangerHandler = new GroupMangerHandler();
		}
		mGroupMangerHandler.deleteGroup(chatId,
				new IRemoveGroupMemberListener() {

					@Override
					public void onRemoveGroupMemberResult(int status) {
						if (status == HttpInvokeResultCode.RESULT_OK) {
							setResult(QUIT_GROUP_TALK);
							finish();
						}
						myHandler.sendEmptyMessage(0);
					}
				});
	}

	/**
	 * 退出群聊
	 *
	 */
	private void exitGroup() {
		tran_loading.setVisibility(View.VISIBLE);
		if (mGroupMangerHandler == null) {
			mGroupMangerHandler = new GroupMangerHandler();
		}
		mGroupMangerHandler.exitGroup(chatId,groupTalk.org_type_id, new IRemoveGroupMemberListener() {

			@Override
			public void onRemoveGroupMemberResult(int status) {
				if (status == HttpInvokeResultCode.RESULT_OK) {
					setResult(QUIT_GROUP_TALK);
					finish();
				}
				myHandler.sendEmptyMessage(0);
			}
		});
	}

	/**
	 * 申请加入群聊
	 */
	private void applyJoinGroup() {
		tran_loading.setVisibility(View.VISIBLE);
		if (mGroupMangerHandler == null) {
			mGroupMangerHandler = new GroupMangerHandler();
		}
		mGroupMangerHandler.applyJoinGroup(chatId,
				new IRemoveGroupMemberListener() {

					@Override
					public void onRemoveGroupMemberResult(int status) {
						myHandler.sendEmptyMessage(0);
					}
				});
	}

	private void updateGroupAvatarDialog() {

		BottomDialog.showBottomDialog(GroupDetailActivity.this, getResources()
						.getString(R.string.take_photo),
				getResources().getString(R.string.take_image), getResources()
						.getString(R.string.cancel), -1,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						takePhoto();
					}
				}, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						pickImage();
					}
				});
	}

	private void showAddGroupMemeberDialog() {
		DialogUtility.showSingleBtnDialog(GroupDetailActivity.this,
				R.string.funds_group_add_memeber, R.string.i_got, true,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
					}
				});
	}

	private void takePhoto() {
		Intent getImageByCamera = new Intent(GroupDetailActivity.this,
				TakePhotoActivity.class);
		ArrayList<ImageSize> size = new ArrayList<ImageSize>();
		size.add(new ImageSize(960, 960, ""));

		Bundle bundle = new Bundle();
		bundle.putSerializable("size", size);
		getImageByCamera.putExtras(bundle);
		startActivityForResult(getImageByCamera, CHOOSE_TAKE_PHOTO_REQUEST_CODE);
	}

	private void pickImage() {
		Intent getImage = new Intent(GroupDetailActivity.this,
				PhotoActivity.class);
		getImage.putExtra("selected_count", 0);
		getImage.putExtra("max_select_count", 1);

		startActivityForResult(getImage, CHOOSE_IMAGE_REQUEST_CODE);
	}

	private void uploadAvatar(byte[] bytes, String url) {
		tran_loading.setVisibility(View.VISIBLE);
		new UploadFile(bytes, new OnUploadFile2Listener() {

			@Override
			public void OnUploadFileSuccess(String response) {
				JSONObject json;
				try {
					json = new JSONObject(response);
					try {
						int status = json.optInt("status");
						String msg = json.optString("msg");
						IMApplication.showToast(msg);
						if (status == HttpInvokeResultCode.RESULT_OK) {
							String small = APIConfiguration.getAvatarUrlNormal(
									chatId, PacketType.GROUP);
							HttpStreamCache.getInstance().ClearCacheBitmap(
									small);
							HttpStreamCache.getInstance().ClearCacheBitmap(
									APIConfiguration.getAvatarUrlBig(chatId,
											PacketType.GROUP));
							talk_detail_avatar.SetUrl(small, true);
						}

					} catch (Exception e) {
					}
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				myHandler.sendEmptyMessage(0);
			}

			@Override
			public void OnUploadFileFail(String response) {
				myHandler.sendEmptyMessage(0);
			}

		}, url);
	}

	@Override
	public void onBackPressed() {
		setBackResult();
		super.onBackPressed();
	}

	@Override
	protected void onResume() {
		if (mUpdateAvatarBroadcast == null) {
			mUpdateAvatarBroadcast = new UpdateAvatarBroadcast();
			IntentFilter filter = new IntentFilter(
					BroadcastAction.ACTION_REFRESH_AVATAR);
			registerReceiver(mUpdateAvatarBroadcast, filter);
		}
		super.onResume();
	}

	private class UpdateAvatarBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if (arg1.getAction().equals(BroadcastAction.ACTION_REFRESH_AVATAR)) {
				talk_detail_avatar.SetUrl(APIConfiguration.getAvatarUrlNormal(
						chatId, PacketType.GROUP));
			}
		}

	}

	@Override
	protected void onDestroy() {
		if (mUpdateAvatarBroadcast != null) {
			unregisterReceiver(mUpdateAvatarBroadcast);
		}
		super.onDestroy();
	}

	private void setGroupNewMsgPush() {
		if (is_remind == 1) {
			new_msg_notify_btn
					.setBackgroundResource(R.drawable.img_button_toggle_on);
		} else {
			new_msg_notify_btn
					.setBackgroundResource(R.drawable.img_button_toggle_off);
		}
		groupTalkDbManager.updateGroupNewMsgPush(Long.valueOf(chatId),
				is_remind);
	}

	private void setBackResult() {
		if (isShowMemberName != is_show_group_member_name
				|| isUpdateNameInGroup == 1) {
			setResult(UPDATE_SHOW_GROUP_MEMBER_NAME);
		}
		finish();
	}

	private void updateMyNameInGroupMenember() {
		if (adapter != null) {
			adapter = null;
		}
		if (participants != null) {
			participants.clear();
		}
		getNewGroup(chatId);
	}
}
